﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace lock语法糖和Monitor
{
    class Program
    {

        /***
         * lock 本质就是利用堆上的同不块实现资源锁定
         * ****/


        static object objLock=new object ();
        static int num = 0;

        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Task.Factory.StartNew(() => {
                    //Run();
                    LockRun();
                });
            }

            Console.ReadLine();
        }

        /// <summary>
        /// 使用lock语法糖
        /// </summary>
        public static void LockRun()
        {
            for (int i = 0; i < 100; i++)
            {
                lock (objLock)
                {
                    Console.WriteLine(num++);
                }

            }
        }

        /// <summary>
        /// 不用lock语法糖
        /// </summary>
        public static void Run()
        {
            for (int i = 0; i < 100; i++)
            {
                bool b = false;
                try
                {
                    Monitor.Enter(objLock, ref b);//锁住一个资源，
                    Console.WriteLine(num++);
                    //Monitor.Exit(objLock);//退出一个资源 
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                { 
                    if(b) Monitor.Exit(objLock);
                }
               
            }
        }
    }
}
